package com.websocket.interceptor;

import com.websocket.Constants;
import com.websocket.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.LinkedList;
import java.util.Map;

@Component
public class GetHeaderParamInterceptor extends ChannelInterceptorAdapter {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RedisService redisService;
    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {


        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
            Object raw = message.getHeaders().get(SimpMessageHeaderAccessor.NATIVE_HEADERS);
            if (raw instanceof Map) {
                Object name = ((Map) raw).get("userid");
                if (name instanceof LinkedList) {
                    // 设置当前访问的认证用户
                    //1. 将用户名存到Redis中
                    //redisService.addToSet(Constants.REDIS_WEBSOCKET_USER_SET, name);
                    logger.debug(MessageFormat.format("WebSocket连接开始创建Principal，用户：{0}", name));
                    accessor.setUser(new MyPrincipal(((LinkedList) name).get(0).toString()));
                }
            }
        }
        return message;
    }
}
